﻿using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using SMARTHOTEL.RoomNum;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Volo.Abp.Application.Services;
using Volo.Abp.Domain.Entities.Auditing;
using Volo.Abp.Domain.Repositories;

namespace SMARTHOTEL.Pictures
{
    [ApiExplorerSettings(GroupName = "v2")]
    public class PicturesService : ApplicationService, IPicturesService
    {
        private readonly IRepository<Picture> repository;
        private readonly IHostingEnvironment hosting;
        private readonly IRepository<PictureRelevance> relevanceRepository;


        public PicturesService(IRepository<Picture> repository, IHostingEnvironment hosting, IRepository<PictureRelevance> relevanceRepository)
        {
            this.repository = repository;
            this.hosting = hosting;
            this.relevanceRepository = relevanceRepository;
        }
        /// <summary>
        /// 添加图片和关联表
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        public async Task<ResultDto<bool>> InsertPicture(PictureDto dto)
        {
            var picture = new Picture
            {
                PictureName = dto.PictureName,
                PictureUrl = dto.PictureUrl
            };
            await repository.InsertAsync(picture);
            var PictureRelevance = new PictureRelevance
            {
                PictureId = picture.Id,
                RelevanceId = dto.Id,
            };
            await relevanceRepository.InsertAsync(PictureRelevance);
            return new ResultDto<bool>
            {
                Data = true,
                Code = StatusCode.Success,
                Msg = "添加成功"
            };
        }
        /// <summary>
        /// 上传文件
        /// </summary>
        /// <param name="file"></param>
        /// <param name="relevanceId"></param>
        /// <returns></returns>
        public async Task<ResultDto<string>> UploadPicture(IFormFile file )
        {
            if (file == null || file.Length == 0)
            {
                return new ResultDto<string>
                {
                    Data = "",
                    Code = StatusCode.Faield,
                    Msg = "文件为空"
                };
            }
            if (file.Length > 2 * 1024 * 1024)
            {
                return new ResultDto<string> { Data = " ", Code = StatusCode.Faield, Msg = "文件大小不能超过 2MB" };
            }
            // 验证文件类型
            string[] allowedExtensions = { ".jpg", ".jpeg", ".png", ".gif", ".bmp" };
            string fileExtension = Path.GetExtension(file.FileName).ToLowerInvariant();
            if (!Array.Exists(allowedExtensions, ext => ext == fileExtension))
            {
                return new ResultDto<string> { Data = " ", Code = StatusCode.Faield, Msg = "仅支持上传 JPG、JPEG、PNG、GIF、BMP 格式的图片" };
            }
            // 时间戳
            string gud = Guid.NewGuid().ToString();

            // 根据时间创建文件夹
            DateTime now = DateTime.Now;
            string yearFolder = now.ToString("yyyy");
            string monthFolder = now.ToString("yyyyMM");
            string dayFolder = now.ToString("yyyyMMdd");

            string basePath = hosting.WebRootPath;
            string folderPath;
            string baseUrl;

            //if (relevanceId == null)
            //{
                folderPath = Path.Combine(basePath, "Img", yearFolder, monthFolder, dayFolder);
                baseUrl = $"https://localhost:7151/Img/{yearFolder}/{monthFolder}/{dayFolder}";
            //}
            //else
            //{
            //    folderPath = Path.Combine(basePath, "Imgfile", yearFolder, monthFolder, dayFolder);
            //    baseUrl = $"https://localhost:7151/Imgfile/{yearFolder}/{monthFolder}/{dayFolder}";
            //}

            // 创建文件夹（如果不存在）
            if (!Directory.Exists(folderPath))
            {
                Directory.CreateDirectory(folderPath);
            }

            // 上传图片地址 图片名称唯一时间戳
            string filePath = Path.Combine(folderPath, gud + file.FileName);
            using (FileStream fs = System.IO.File.Create(filePath))
            {
                await file.CopyToAsync(fs);
            }

            //if (relevanceId == null)
            //{
                return new ResultDto<string>{ Data = $"{baseUrl}/{gud + file.FileName}", Code = StatusCode.Success, Msg = "图片上传成功" };
            //}
            //else
            //{
            //    var result=await InsertPicture(new PictureDto { PictureName = file.FileName, PictureUrl = $"{baseUrl}/{gud + file.FileName}", Id = relevanceId });

            //    return new ResultDto<string> { Data = result, Code = StatusCode.Success, Message = "图片上传成功" };
            //}

        }
    }
}
